package com.qyhl.webtv.module_live.utils;


import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.entity.live.TeleTextLiveBean;
import com.qyhl.webtv.commonlib.utils.view.ScoopButton;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by qyhl2 on 2017/8/8.
 */

public class MediaListManager {

    private MediaPlayer mMediaPlayer;

    private boolean isPause = false;//是否是暂停

    OnProgressListener proListener;
    private Timer mTimer;
    private TimerTask mTimerTask;

    public TeleTextLiveBean getContentBean() {
        return contentBean;
    }

    public void setContentBean(TeleTextLiveBean contentBean) {
        this.contentBean = contentBean;
    }

    private TeleTextLiveBean contentBean;

    private static MediaListManager mediaManager;
    private ScoopButton audieoTe;

    public Integer getmContentId() {
        return mContentId;
    }

    public void setmContentId(Integer mContentId) {
        this.mContentId = mContentId;
    }

    private Integer mContentId;

    private MediaListManager() {
    }

    public static MediaListManager getIntance() {
        if (mediaManager == null) {
            mediaManager = new MediaListManager();
        }
        return mediaManager;
    }


    public boolean isPlay() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    /**
     * 播放音频
     */
    public void playSound(String filePath, MediaPlayer.OnCompletionListener onCompletionListener) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mMediaPlayer.reset();
                    return false;
                }
            });
        } else {
            mMediaPlayer.reset();
        }
        try {
            mMediaPlayer.setAudioStreamType(android.media.AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(onCompletionListener);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            mMediaPlayer.prepareAsync();
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {

                    try {
                        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                            double cp = Double.parseDouble(mMediaPlayer.getCurrentPosition() + "");
                            double t = 1000;
                            DecimalFormat df = new DecimalFormat("0");
                            String timeStr = df.format(cp / t);
                            Message m = new Message();
                            m.what = 0;
                            Bundle bun = new Bundle();
                            bun.putString("pro", StringUtils.intToString(Integer.parseInt(timeStr)));
                            m.setData(bun);
                            handleProgress.handleMessage(m);
//                        Log.e("mTimerTask",mMediaPlayer.getDuration()+"*****"+mMediaPlayer.getCurrentPosition());
                        }
                    } catch (IllegalStateException e) {
                    }


                }
            };
            mTimer.schedule(mTimerTask, 0, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void playSound(Context c, String filePath, MediaPlayer.OnCompletionListener onCompletionListener) {
        if (mMediaPlayer == null) {
//            mMediaPlayer = new MediaPlayer();
            mMediaPlayer = MediaPlayer.create(c, Uri.parse(filePath));
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mMediaPlayer.reset();
                    return false;
                }
            });
        } else {
            mMediaPlayer.reset();
        }
        try {
            mMediaPlayer.setAudioStreamType(android.media.AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(onCompletionListener);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    //停止视频播放

                }
            });
            mMediaPlayer.prepareAsync();
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    try {
                        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                            double cp = Double.parseDouble(mMediaPlayer.getCurrentPosition() + "");
                            double t = 1000;
                            DecimalFormat df = new DecimalFormat("0");
                            String timeStr = df.format(cp / t);
                            Message m = new Message();
                            m.what = 0;
                            Bundle bun = new Bundle();
                            bun.putString("pro", StringUtils.intToString(Integer.parseInt(timeStr)));
                            m.setData(bun);
                            handleProgress.handleMessage(m);
//                        Log.e("mTimerTask",mMediaPlayer.getDuration()+"*****"+mMediaPlayer.getCurrentPosition());
                        }
                    } catch (IllegalStateException e) {
                    }
                }
            };
            mTimer.schedule(mTimerTask, 0, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    Handler handleProgress = new MyHandler(this);


    private static class MyHandler extends Handler {
        private final WeakReference<MediaListManager> mManager;

        public MyHandler(MediaListManager activity) {
            mManager = new WeakReference<MediaListManager>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            MediaListManager mediaListManager =  mManager.get();
            Bundle bun = msg.getData();
            String pro = bun.getString("pro");
            int id = ((TeleTextLiveBean) mediaListManager.audieoTe.getTag()).getId();
            if (mediaListManager.contentBean.getId() == id) {
                mediaListManager.proListener.Onprogress(mediaListManager.audieoTe, pro);
            } else {
                mediaListManager.proListener.Onprogress(mediaListManager.audieoTe, ((TeleTextLiveBean) mediaListManager.audieoTe.getTag()).getAudioDuration());
                mediaListManager.mMediaPlayer.reset();
            }
        }




    }




    /**
     * 暂停
     */
    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            isPause = true;
        }
    }

    /**
     * 继续
     */
    public void resume() {
        if (mMediaPlayer != null && isPause) {
            mMediaPlayer.start();
            isPause = false;
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mTimer.cancel();
            mTimerTask.cancel();
            mTimer = null;
            mMediaPlayer = null;
        }
    }



    public void setOnProgressListener(OnProgressListener lis) {
        this.proListener = lis;
    }

    public void setTextView(ScoopButton audioTe) {
        this.audieoTe = audioTe;
    }

    public ScoopButton getTextView() {
        return audieoTe;
    }

    public interface OnProgressListener {
        void Onprogress(ScoopButton te, String pro);
    }
}
